package org.papervision3d.view;

import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.events.Event;
import nme.geom.Matrix;

import org.papervision3d.core.render.data.RenderSessionData;
import org.papervision3d.core.view.IViewport3D;

/**
 * @Author Ralph Hauwert
 */
class BitmapViewport3D extends Viewport3D, implements IViewport3D
{
	
	public var bitmapData		:BitmapData;
	
	public var _containerBitmap	:Bitmap;
	protected var _fillBeforeRender:Bool = true;
	protected var bgColor			:Int;
	protected var bitmapTransparent:Bool;
	
	public function new(viewportWidth:Number=640, viewportHeight:Number=480, autoScaleToStage:Bool = false,bitmapTransparent:Bool=false, bgColor:Int=0x000000,  interactive:Bool=false, autoCulling:Bool=true)
	{
		super(viewportWidth, viewportHeight, autoScaleToStage, interactive, true, autoCulling);
		this.bgColor = bgColor;
		_containerBitmap = new Bitmap();
		
		bitmapData = _containerBitmap.bitmapData = new BitmapData(Math.round(viewportWidth), Math.round(viewportHeight), bitmapTransparent, bgColor);		
		scrollRect = null;
		addChild(_containerBitmap);
		removeChild(_containerSprite);		
	}
	
	override public function updateAfterRender(renderSessionData:RenderSessionData):Void
	{
		super.updateAfterRender(renderSessionData);
		if(bitmapData.width != Math.round(viewportWidth) || bitmapData.height != Math.round(viewportHeight))
		{
			bitmapData = _containerBitmap.bitmapData = new BitmapData(Math.round(viewportWidth), Math.round(viewportHeight), bitmapTransparent, bgColor);
		}
		else
		{
			if(_fillBeforeRender){
				bitmapData.fillRect(bitmapData.rect, bgColor);
			}
		}

		var mat:Matrix = new Matrix();
		mat.translate(_hWidth, _hHeight);
		bitmapData.draw(_containerSprite, mat ,null, null, bitmapData.rect, false);
	}
	
	override private function onStageResize(event:Event = null):Void
	{
		if(_autoScaleToStage)
		{
			viewportWidth = stage.stageWidth;
			viewportHeight = stage.stageHeight;
		}
	}
	
	public var fillBeforeRender(get_fillBeforeRender, set_fillBeforeRender):Bool;
	private function set_fillBeforeRender(value:Bool):Bool
	{
		_fillBeforeRender = value;	
		return value;
	}
	
	private function get_fillBeforeRender():Bool
	{
		return _fillBeforeRender;
	}
	
	public var autoClipping(get_autoClipping, set_autoClipping):Bool;
	override private function set_autoClipping(clip:Bool):Bool
	{
		//Do nothing.
		return clip;	
	}
	
	override private function get_autoClipping():Bool
	{
		return _autoClipping;	
	}
}